<template>
  <div class="box">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3 style="display: inline">提示文本：</h3>
          <el-button class="button" type="primary" style="float:right;" round
                     @click="onClose">
            关闭
          </el-button>
        </div>
      </template>
      <div class="text-item" v-html="prompt"/>
      <el-divider/>
      <generate-parameter-setter ref="generateParameterSetter" :editable="false"/>
    </el-card>
    <el-card class="box-card" v-loading="loading"
             element-loading-text="模型生成中">
      <template #header>
        <div class="card-header">
          <h3 style="display: inline">生成结果：</h3>
        </div>
      </template>
      <div class="text-item" v-html="text"/>
      <el-divider/>
      <h4>困惑度：{{ perplexity }}</h4>
    </el-card>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import GenerateParameterSetter from "./GenerateParameterSetter.vue";

export default {
  name: "RawTextGenerateTaskCard",
  components: {
    GenerateParameterSetter
  },
  data() {
    return {
      loading: true,
      text: '',
      perplexity: 0.0,
    }
  },
  props: {
    prompt: String,
    cardIndex: Number,
    maxLength: Number,
    temperature: Number,
    topK: Number,
    topP: Number
  },
  mounted() {
    let generateParameterSetter = this.$refs.generateParameterSetter
    generateParameterSetter.table.maxLength = this.maxLength
    generateParameterSetter.table.temperature = this.temperature
    generateParameterSetter.table.topK = this.topK
    generateParameterSetter.table.topP = this.topP

    this.axios.get('/generate', {
      params: {
        prompt: this.prompt,
        max_length: this.maxLength,
        temperature: this.temperature,
        top_k: this.topK,
        top_p: this.topP,
      }
    }).then(response => {
      this.text = this.formatHTMLString(response.data.generated)
      this.perplexity = response.data.perplexity
      this.loading = false
    }).catch(err => {
      ElMessage('获取文本生成结果' + this.prompt + '失败, 详情见控制台')
      console.log(err)
      this.loading = false
    })
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    // todo: 转换为工具函数
    formatHTMLString(string) {
      // 回车
      string = string.replace(/\r\n/g, "<br>").replace(/\n/g, "<br>").replace(/\r/g, "<br>");
      return string
    },
  }
}
</script>

<style scoped>
.box {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 20px 2px 6px rgba(0, 0, 0, .04);
  border-radius: 4px;
  padding: 5px 10px 10px 10px;
}

.card-header {
  text-align: left;
}

.text-item {
  text-align: left;
}

.box-card {
  width: 100%;
  text-align: left;
  margin-top: 10px;
}
</style>